﻿using System;

namespace OscarCloverActivities.Packets
{
    public class Tlv:IComparable<Tlv>
    {
        public byte[] Value { get; set; }

        public ushort Tag { get; set; }

        public ushort Len { get; set; }

        public Tlv(ushort tag, byte[] value)
        {
            Value = new byte[(value).Length];
            Array.Copy(value, Value, (value).Length);
            Len = (ushort) (value).Length;
            Tag = tag;
        }

        public Tlv(ushort tag, UInt16 value)
        {
            Value = new byte[2];
            Value[0] = (byte) ((value >> 8) & (0xff));
            Value[1] = (byte) (value & (0xff));
            Len = 2;
            Tag = tag;
        }
        
        
        public Tlv(ushort tag, UInt32 value)
        {
            Value = new byte[4];
            Value[0] = (byte) ((value >> 24) & (0xff));
            Value[1] = (byte) ((value >> 16) & (0xff));
            Value[2] = (byte) ((value >> 8) & (0xff));
            Value[3] = (byte) (value & (0xff));
            Len = 4;
            Tag = tag;
        }

        public Tlv(ushort tag, byte value)
        {
            Value = new byte[1];
            Value[0] = value;
            Len = 1;
            Tag = tag;
        }

        public Tlv(ushort tag, string value)
        {
            Value = new byte[(value).Length];
            for (int i = 0; i < (value).Length; i++)
            {
                Value[i] = (byte) (value)[i];
            }
            Len = (ushort) ((value).Length);
            Tag = tag;
        }

        public byte[] GetBytes()
        {
            var _return = new byte[4 + Len];
            _return[0] = (byte) ((Tag >> 8) & (0xff));
            _return[1] = (byte) (Tag & (0xff));
            _return[2] = (byte) ((Len >> 8) & (0xff));
            _return[3] = (byte) (Len & (0xff));
            Array.Copy(Value, 0, _return, 4, Len);
            return _return;
        }

        public int CompareTo(Tlv other)
        {
            return Tag.CompareTo(other.Tag);
        }
    }
}